<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="盈亏单编号" prop="suCode">
        <el-input
          v-model="queryParams.suCode"
          placeholder="请输入盈亏单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盈亏单名称" prop="suName">
        <el-input
          v-model="queryParams.suName"
          placeholder="请输入盈亏单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
<!--    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:surplus:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:surplus:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:surplus:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wm:surplus:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="surplusList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="盈亏单编号" align="center" prop="suCode" width="150">
      <template slot-scope="scope">
        <el-button
          type="text"
          @click="handleView(scope.row)"
        >{{scope.row.suCode}}</el-button>
      </template>
      </el-table-column>
      <el-table-column label="盈亏单名称" align="center" prop="suName" />
      <el-table-column label="盈亏类型" align="center" prop="suType" />
      <el-table-column label="库存盘点单编码" align="center" prop="workorderCode" />

      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库区" align="center" prop="locationName" />
      <el-table-column label="库位" align="center" prop="areaName" />
      <el-table-column label="盈亏单日期" align="center" prop="suDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.suDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      20250423以前保存的待审核  已审核  现在保存0待  1已  -->
      <el-table-column label="单据状态" align="center" prop="status" >
      <template slot-scope="scope">
        <el-tag v-if="scope.row.status === '已审核'|| scope.row.status === '1'"  type="success">已处理</el-tag>
        <el-tag v-if="scope.row.status === '待审核' || scope.row.status === '0'"  type="warning">待处理</el-tag>

      </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="操作" align="center"  width="180px">
        <template slot-scope="scope">

            <el-button
                       size="mini"
                       type="text"
                       icon="el-icon-s-check"
                       @click="handleView(scope.row)"
                       v-if="scope.row.status == '待审核' || scope.row.status === '0'"
                       v-hasPermi="['mes:wm:pandian:edit']"
            >处理</el-button>

<!--          <el-tooltip content="编辑" placement="top" v-if="scope.row.status == '待审核'">
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:surplus:edit']"
          ></el-button>
          </el-tooltip>-->

<!--          <el-tooltip content="删除" placement="top"  v-if="scope.row.status == '待审核'">
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wm:surplus:remove']"
          ></el-button>
          </el-tooltip>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改盈亏单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body @close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px"  >
        <el-row>
          <el-col :span="8">
            <el-form-item label="盈亏单编号" prop="suCode">
              <el-input v-model="form.suCode" placeholder="请输入入库单编号" :disabled="optType == 'add' ? false:true"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)">
              </el-switch>
            </el-form-item>
          </el-col>-->

          <el-col :span="8">
            <el-form-item label="盈亏单名称" prop="suName">
              <el-input v-model="form.suName" placeholder="请输入盈亏单名称" :disabled="optType == 'add' ? false:true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盈亏单日期" prop="suName">
<!--              <el-input v-model="form.suDate" placeholder="请输入盈亏单日期" />-->
              <el-date-picker v-model="form.suDate" value-format="yyyy-MM-dd" type="date"
                              :disabled="form.status == '1'" style="width: 100%"
                              :default-value="new Date()"
                              placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-input v-model="form.warehouseName" :disabled="optType == 'add' ? false:true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库区" prop="locationName">
              <el-input v-model="form.locationName" :disabled="optType == 'add' ? false:true"></el-input>
            </el-form-item>
          </el-col>

<!--          <el-col :span="12">
            <el-form-item label="仓库">
              <el-cascader v-model="warehouseInfo" ref="selectck"
                           :options="warehouseOptions"
                           :props="warehouseProps"
                           style="width:100%"
                           @change="handleWarehouseChanged"
              >
              </el-cascader>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库位" prop="areaName">
              <el-input v-model="form.areaName" :disabled="optType == 'add' ? false:true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盈亏单类型">
              <el-select v-model="form.suType" placeholder="请选择盈亏类型" clearable style="width: 100%" :disabled="optType == 'add' ? false:true">
                <el-option label="盘盈" value="盘盈"></el-option>
                <el-option label="盘亏" value="盘亏"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="optType == 'add' ? false:true"/>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="form.suId !=null" content-position="center">物料信息</el-divider>
      <el-card shadow="always" v-if="form.suId !=null" class="box-card">
        <Surplusline ref="chiledForm" :suId="form.suId" :warehouseInfo="warehouseInfo" :optType="optType" ></Surplusline>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleShenHe(form)" v-if="confirm === true">处理</el-button>
        <el-button type="primary" @click="cancel" v-if="optType =='view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType !='view' ">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSurplus, getSurplus, delSurplus, addSurplus, updateSurplus,addProducts,shenHe } from "@/api/mes/wm/surplus";
import {genCode} from "@/api/system/autocode/rule";
import {getTreeList} from "@/api/mes/wm/warehouse";
import Surplusline from "./line.vue";
import {execute} from "@/api/mes/wm/itemrecpt";

export default {
  name: "Surplus",
  components: {Surplusline},
  data() {
    return {
      optType: undefined,
      confirm: false,
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      autoGenFlag: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盈亏单表格数据
      surplusList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        suCode: null,        suName: null,        workorderCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,        status: null,        updateByName: null,        tenantId: null      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        suDate: [
          { required: true, message: "盈亏单日期不能为空", trigger: "blur" }
        ],      }
    };
  },
  created() {
    this.warehouseInfo=[]
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    handleClose(){
      this.cancel()
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('YINGKUI_CODE').then(response => {
          this.form.suCode = response;
        });
      } else {
        this.form.suCode = null;
      }
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      console.log(111111)
      const selectedNodes = this.$refs.selectck.getCheckedNodes();
      if(obj !=null){
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
        this.form.warehouseName=selectedNodes[0].pathLabels[0]
        this.form.locationName=selectedNodes[0].pathLabels[1]
        this.form.areaName=selectedNodes[0].pathLabels[2]
      }
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
          ;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    /** 查询盈亏单列表 */
    getList() {
      this.loading = true;
      listSurplus(this.queryParams).then(response => {
        this.surplusList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        suId: null,        suCode: null,        suName: null,        workorderId: null,        workorderCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,
        suDate: new Date().toISOString().split('T')[0],        status: null,        remark: null,        attr1: null,        attr2: null,        attr3: null,        attr4: null,        createBy: null,        createByName: null,        createTime: null,        updateBy: null,        updateByName: null,        updateTime: null,        tenantId: null ,suType:null     };

      this.resetForm("form");
      this.autoGenFlag = false;
      this.confirm = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.suId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.warehouseInfo=[]
      this.open = true;
      this.title = "添加盈亏单";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset()
      this.warehouseInfo=[]
      const suId = row.suId || this.ids
      getSurplus(suId).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] =response.data.warehouseId ;
        this.warehouseInfo[1] =response.data.locationId ;
        this.warehouseInfo[2] = response.data.areaId;
        this.getWarehouseList();
        this.$forceUpdate()
        this.open = true;
        this.optType = "view";
        this.title = "盈亏单详情";
        if(response.data.status === '待审核' || response.data.status === '0'){
          this.confirm = true;
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.warehouseInfo=[]
      const suId = row.suId || this.ids
      getSurplus(suId).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] =response.data.warehouseId ;
        this.warehouseInfo[1] =response.data.locationId ;
        this.warehouseInfo[2] = response.data.areaId;
        this.getWarehouseList();
        this.$forceUpdate()
        this.open = true;
        this.optType = "edit";
        this.title = "修改盈亏单";
      })
    },
    handleShenHe(row){
      this.$modal.confirm('确定审核并进行库存更改？').then(function () {
        return shenHe(row.suId)//执行入库
      }).then(() => {
        this.cancel();
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.optType == 'edit'){
        const childForm = this.$refs.chiledForm;
        this.$refs.chiledForm.submitGoodsInventoryAddForm()
        this.open = false;
        this.getList();
      }
      if(this.optType == 'add'){
        console.log("form",this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.suId != null) {
              console.log("form",this.form)
              updateSurplus(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSurplus(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const suIds = row.suId || this.ids;
      this.$modal.confirm('是否确认删除盈亏单编号为"' + suIds + '"的数据项？').then(function() {
        return delSurplus(suIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/surplus/export', {
        ...this.queryParams
      }, `surplus_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
